package com.boardour.wifip2p.popup;

import android.app.Activity;
import android.content.DialogInterface;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.view.View;

import androidx.appcompat.app.AlertDialog;

import com.boardour.wifip2p.R;
import com.boardour.wifip2p.WifiP2pCommon;

import cn.carhouse.adapter.XQuickAdapter;
import cn.carhouse.adapter.XQuickViewHolder;

/**
 * WifiP2p列表适配器
 */
public class WifiP2pListAdapter extends XQuickAdapter<WifiP2pDevice> {
    private boolean isAutoDisconnect = true;

    public WifiP2pListAdapter(Activity activity) {
        super(activity, R.layout.wifip2p_list_dialog_item);
    }

    public void setAutoDisconnect(boolean autoDisconnect) {
        isAutoDisconnect = autoDisconnect;
    }

    @Override
    protected void convert(XQuickViewHolder holder, final WifiP2pDevice item, int position) {
        holder.setText(R.id.tv_name, item.deviceName);
        holder.setText(R.id.tv_state, WifiP2pCommon.getDeviceStatus(item.status));
        if (item.status == WifiP2pDevice.CONNECTED) {
            WifiP2pCommon.getInstance().stopPeerDiscovery();
        }
        holder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                connect(item);
            }
        });
    }

    private void connect(WifiP2pDevice item) {
        // 再次点击就取消连接
        if (isAutoDisconnect && item.status != WifiP2pDevice.AVAILABLE) {
            showDisconnect(item);
            return;
        }
        final WifiP2pConfig config = new WifiP2pConfig();
        config.deviceAddress = item.deviceAddress;
        config.groupOwnerIntent = WifiP2pConfig.GROUP_OWNER_INTENT_MIN;
        config.wps.setup = WpsInfo.PBC;
        WifiP2pCommon.getInstance().connect(config);
    }

    private void showDisconnect(WifiP2pDevice item) {
        new AlertDialog.Builder(mActivity)
                .setTitle("断开" + item.deviceName + "连接")
                .setMessage("确定断开" + item.deviceName + "连接吗?")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        WifiP2pCommon.getInstance().cancelAndRemoveConnect();
                    }
                })
                .setNegativeButton("取消", null)
                .show();

    }


}
